package com.fjnu.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.util.Date;

/**
 * @desc: AOP切面用于日志记录
 */
@Aspect
@Configuration
public class LoggingAspect {

    /**
     * 切入点：所有DAO层的方法
     */
    @Pointcut("execution(* com.fjnu.dao.impl.*.*(..))")
    public void daoMethods() {}

    /**
     * 环绕通知：记录方法执行日志
     */
    @Around("daoMethods()")
    public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        long startTime = System.currentTimeMillis();

        try {
            Object result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            double elapsedTime = (endTime - startTime) / 1000.0;

            // 格式化日志输出
            String logMessage = String.format("[INFO][%tF %tT] %s was executed and spent %.1f second.",
                    new Date(), new Date(), methodName, elapsedTime);
            System.out.println(logMessage);

            return result;
        } catch (Throwable throwable) {
            long endTime = System.currentTimeMillis();
            double elapsedTime = (endTime - startTime) / 1000.0;

            String errorLog = String.format("[ERROR][%tF %tT] %s failed after %.1f second with exception: %s",
                    new Date(), new Date(), methodName, elapsedTime, throwable.getMessage());
            System.out.println(errorLog);
            throw throwable;
        }
    }
}